package service

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"math/rand"
	"time"
	"user_srv/basic/config"
	__ "user_srv/basic/proto"
	"user_srv/handler/models"
	"user_srv/pkg"
	"user_srv/untils"
)

type Server struct {
	__.UnimplementedUserServer
}

// 发送验证码
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	count := config.Rdb.Get(config.Ctx, "sendSmsErr"+in.Mobile).Val()
	if count == "3" {
		return nil, fmt.Errorf("请等待一分钟后再试")
	}

	//sendSms := untils.Sms{}
	code := rand.Intn(9000) + 1000
	//err := sendSms.SendSms(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	config.Rdb.Set(config.Ctx, "sendSms"+in.Mobile, code, time.Minute)
	config.Rdb.Incr(config.Ctx, "sendSmsErr"+in.Mobile)
	config.Rdb.Expire(config.Ctx, "sendSmsErr"+in.Mobile, time.Minute)
	return &__.SendSmsResp{}, nil
}

// 用户注册
func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	sms := config.Rdb.Get(config.Ctx, "sendSms"+in.Mobile).Val()
	var user models.User
	user.Mobile = in.Mobile
	user.Password = pkg.Md5(in.Password)
	err := user.GetUserByMobile()
	if err != nil {
		return nil, fmt.Errorf("获取用户信息失败")
	}
	if user.Id != 0 {
		return nil, fmt.Errorf("该账号已注册，请前去登录")
	}
	if sms != in.SmsCode {
		return nil, fmt.Errorf("验证码错误，请稍后再试")
	}

	err = user.CreateUser()
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	return &__.RegisterResp{
		UserId: int64(user.Id),
	}, nil
}

// 登录
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	sms := config.Rdb.Get(config.Ctx, "sendSms"+in.Mobile).Val()
	var user models.User
	user.Mobile = in.Mobile
	user.Password = pkg.Md5(in.Password)
	err := user.GetUserByMobile()
	if err != nil {
		return nil, fmt.Errorf("获取用户信息失败")
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("该账号不存在")
	}
	if sms != in.SmsCode {
		return nil, fmt.Errorf("验证码错误，请稍后再试")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误")
	}

	return &__.LoginResp{
		UserId: int64(user.Id),
	}, nil
}

// 切换司机
func (s *Server) UpdateUser(_ context.Context, in *__.UpdateUserReq) (*__.UpdateUserResp, error) {
	var user models.User
	user.Id = uint(in.UserId)

	err := user.GetUserById()
	if err != nil {
		return nil, fmt.Errorf("获取司机信息失败")
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("该用户不存在")
	}
	user.UserType = uint(in.UserType)
	err = user.UpdateUser()
	if err != nil {
		return nil, fmt.Errorf("用户司机切换失败" + err.Error())
	}

	return &__.UpdateUserResp{
		UserId: int64(user.Id),
	}, nil
}

// 添加司机
func (s *Server) AddDirvers(_ context.Context, in *__.AddDirversReq) (*__.AddDirversResp, error) {
	var dirver models.Driver
	dirver.UserId = uint(in.UserId)
	dirver.DriverLicenseUrl = in.DriverLicenseUrl
	dirver.LicenseNumber = uint(in.LicenseNumber)
	dirver.CarType = in.CarType
	err := dirver.CreateDriver()
	if err != nil {
		return nil, fmt.Errorf("添加司机失败")
	}

	return &__.AddDirversResp{
		DiverId: int64(dirver.Id),
	}, nil
}

// 审核司机
func (s *Server) CheckDirverStatus(_ context.Context, in *__.CheckDirverStatusReq) (*__.CheckDirveStatusResp, error) {
	var dirver models.Driver
	dirver.Id = uint(in.UserId)
	dirver.Status = uint(in.Status)
	err := dirver.GetDirverById()
	if err != nil {
		return nil, fmt.Errorf("获取司机信息失败")
	}
	if dirver.Id == 0 {
		return nil, fmt.Errorf("未找到该司机")
	}

	err = dirver.CheckDirverStatus()
	if err != nil {
		return nil, fmt.Errorf("修改失败")
	}
	return &__.CheckDirveStatusResp{
		Id: int64(dirver.Id),
	}, nil
}

// 绑定车辆
func (s *Server) BrandDirverCar(_ context.Context, in *__.BrandDirverCarReq) (*__.BrandDirverCarResp, error) {
	var car models.Car
	car.DriverId = uint(in.DriverId)
	car.LicenseNumber = in.LicenseNumber
	car.Brand = in.Brand
	car.Model = in.Model
	car.Color = in.Color
	car.Seat = uint(in.Seat)
	car.CarsUrl = in.CarsUrl
	err := car.BrandDirverCar()
	if err != nil {
		return nil, fmt.Errorf("绑定失败")
	}
	return &__.BrandDirverCarResp{
		Id: int64(car.Id),
	}, nil
}

// 创建订单
func (s *Server) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {
	kilo := rand.Intn(int(in.Kilometer))
	order := models.Order{
		UserId:    uint(in.UserId),
		DriverId:  uint(in.DirverId),
		OrderSn:   uuid.NewString(),
		Start:     in.Start,
		End:       in.End,
		Kilometer: float64(kilo),
		Total:     models.GetOrder(float64(kilo), int(in.DirverId)),
	}
	err := order.CreateOrder()
	untils.SyncToEs()
	if err != nil {
		return nil, fmt.Errorf("订单创建失败")
	}
	return &__.CreateOrderResp{
		OrderId: int64(order.Id),
	}, nil
}

// 车型列表
func (s *Server) CarTypeList(_ context.Context, in *__.CarTypeListReq) (*__.CarTypeListResp, error) {
	carlist := config.Rdb.Get(config.Ctx, "carList").Val()
	var car models.Car
	car.Model = in.Model
	var CarList []*__.CarTypeList
	if carlist == "" {
		cartType, err := car.CartType()
		if err != nil {
			return nil, fmt.Errorf("列表信息展示失败")
		}
		for _, c := range cartType {
			CarList = append(CarList, &__.CarTypeList{
				DriverId: int64(c.DriverId),
				Brand:    c.Brand,
				Model:    c.Model,
			})
		}
		marshal, _ := json.Marshal(&cartType)
		config.Rdb.Set(config.Ctx, "carList", marshal, time.Minute*5)
	} else {
		json.Unmarshal([]byte(carlist), &carlist)
	}

	return &__.CarTypeListResp{
		List: CarList,
	}, nil
}

// 接单模式
func (s *Server) UpdateOrder(_ context.Context, in *__.UpdateOrderReq) (*__.UpdateOrderResp, error) {
	var order models.Order
	order.Id = uint(in.Id)
	err := order.GetOrderDirver()
	if err != nil {
		return nil, fmt.Errorf("获取司机信息失败")
	}
	if order.Id == 0 {
		return nil, fmt.Errorf("没有找到该司机")
	}
	order.TakingOrder = uint(in.TakingOrder)
	err = order.UpdateOrder()
	if err != nil {
		return nil, fmt.Errorf("修改信息失败")
	}
	return &__.UpdateOrderResp{
		Id: int64(order.Id),
	}, nil
}

// 订单详情
func (s *Server) OrderDetail(_ context.Context, in *__.OrderDetailReq) (*__.OrderDetailResp, error) {
	var order models.Order
	order.Id = uint(in.Id)
	err := order.OrderDetail()
	if err != nil {
		return nil, fmt.Errorf("获取订单详情失败")
	}

	var user models.User
	user.Status = 2
	err = user.UpdateUserStatus(int(order.DriverId))
	if err != nil {
		return nil, fmt.Errorf("司机接单失败")
	}
	return &__.OrderDetailResp{
		UserId:    int64(order.UserId),
		DirverId:  int64(order.DriverId),
		Start:     order.Start,
		End:       order.End,
		Kilometer: float32(order.Kilometer),
	}, nil
}

// 修改订单状态
func (s *Server) UpdateOrderStatus(_ context.Context, in *__.UpdateOrderStatusReq) (*__.UpdateOrderStatusResp, error) {
	var order models.Order
	order.Id = uint(in.Id)

	err := order.GetOrderId()
	if err != nil {
		return nil, fmt.Errorf("获取订单信息失败")
	}
	if order.Id == 0 {
		return nil, fmt.Errorf("没有此订单")
	}
	order.Status = uint(in.Status)
	err = order.UpdateOrderStatus()

	alipay := untils.Pay{}
	fmt.Println(alipay.AliPay(order.OrderSn, fmt.Sprintf("%.2f", order.Total)))

	if err != nil {
		return nil, fmt.Errorf("修改订单状态失败")
	}
	return &__.UpdateOrderStatusResp{
		Id: int64(order.Id),
	}, nil
}

// 我的订单
func (s *Server) MyOrdersList(_ context.Context, in *__.MyOrdersListReq) (*__.MyOrdersListResp, error) {
	var order models.Order
	order.UserId = uint(in.UserId)
	var List []*__.MyOrdersList
	myOrder, err := order.MyOrder()
	if err != nil {
		return nil, fmt.Errorf("我的订单展示失败")
	}
	for _, m := range myOrder {
		List = append(List, &__.MyOrdersList{
			UserId:    int64(m.UserId),
			DirverId:  int64(m.DriverId),
			Start:     m.Start,
			End:       m.End,
			Kilometer: float32(m.Kilometer),
			Total:     float32(m.Total),
		})
	}
	return &__.MyOrdersListResp{
		List: List,
	}, nil
}
